import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

public class RThreads extends Thread {

    private String[] CommandString;
    private Process Process;
    private boolean Finished = false;
    private boolean Printable = true;
    private BufferedReader Bufferedreader;
    private int ReturnCode;
    private String OutputString; 
    
    public int getReturnCode() 
    	{	return ReturnCode;    }

    public void setReturnCode(int returnCode) 
    	{	ReturnCode = returnCode;    }

    public String getOutputString() 
    	{	return OutputString;    }

    public void setOutputString(String outputString) 
    	{	OutputString = outputString;    }

    public void setFinished(boolean finished) 
    	{	Finished = finished;    }

    public String[] getCommandString() 
 	{	return CommandString;	}

     public void setCommandString( String[] commandString ) 
 	{	CommandString = commandString;	}
     	
     public boolean isFinished() 
     	{	return Finished;    }

     public void SetFinished() 
 	{	Finished = true;    }
     
     public boolean isPrintable() 
     	{	return Printable;    }

     public void setPrintable(boolean printable) 
     	{	Printable = printable;    }


    public RThreads( boolean isPrintable, String[] Command ) throws IOException 
    	{	
		this.CommandString = Command;
    		this.Printable = isPrintable;
    		ProcessBuilder builder = new ProcessBuilder( Command );
    		builder.redirectErrorStream( true );
    		this.Process = builder.start();

    		InputStream inputstream = Process.getInputStream();
    		InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
    		
    		this.Bufferedreader = new BufferedReader(inputstreamreader);
    		this.start();
    	}
    	
     
    @Override
    public void run() 
    {
	try 
	{	int returnCode = Process.waitFor();
		setReturnCode( returnCode );	} 
	catch (Exception e) 
	{	e.printStackTrace();	}
	
	Finished = true;
	String line = "";
	boolean isFirstLine = true;
	String date = "";
	String WholeString = "";
	
	if ( isPrintable() == true )
	{	Date dateD = new Date();
		date = dateD.toString();		}

	try 
	{
	    while (( line = Bufferedreader.readLine() ) != null ) 
	    {
	        if ( isPrintable() )
	        {	
	    		if ( isFirstLine )
	    		{	
	    		    FileOutput.printCommandHeader( CommandString, ReturnCode, date );
	    		    isFirstLine = false;	
	    		}
	    		FileOutput.AppendToStandardOutput( line );	
	        }	
	    
	        WholeString = WholeString + line + "\n" ;							
	    }
	} catch (IOException e) 
		{    e.printStackTrace();	}
	
	WholeString = WholeString.replaceAll("\n$", "");
	setOutputString( WholeString );
    }

}

